package com.gcy.wanandroid.ui.activity.main;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import com.gcy.wanandroid.base.viewmodel.BaseViewModel;
import com.gcy.wanandroid.bean.responsebean.LoginBean;
import com.gcy.wanandroid.config.Constants;
import com.gcy.wanandroid.http.data.HttpDisposable;
import com.gcy.wanandroid.http.request.HttpFactory;
import com.gcy.wanandroid.http.request.HttpRequest;
import com.gcy.wanandroid.util.CommonUtils;
import com.orhanobut.hawk.Hawk;

/**
 * @author: gcy
 * @description: 主页ViewModel
 * @version: 1.0
 * @CreateTime: 2023-05-18  13:20
 */
public class MainViewModel extends BaseViewModel {

    private MutableLiveData<LoginBean> userBean;
    private MutableLiveData<String> userHeader;

    public MainViewModel() {
        userBean = new MutableLiveData<>();
        userHeader = new MutableLiveData<>();
    }

    //获取用户信息
    public LiveData<LoginBean> getUserBean() {
        return userBean;
    }
    //获取用户头像
    public LiveData<String> getUserHeader() {
        return userHeader;
    }

    //获取缓存的用户信息
    public void getUserData() {
        LoginBean loginBean = Hawk.get(Constants.HawkCode.LOGIN_DATA);
        if (loginBean != null) {
            //自动登录

        }
    }

    //自动登录
    private void login(String name, String pwd) {
        HttpRequest.getInstance()
                .Login(name, pwd)
                .compose(HttpFactory.schedulers())
                .subscribe(new HttpDisposable<LoginBean>() {
                    @Override
                    public void success(LoginBean loginBean) {
                        //自动登录成功
                        userBean.postValue(loginBean);
                        loginBean.setPassword(pwd);
                        Hawk.put(Constants.HawkCode.LOGIN_DATA, loginBean);
                        loadUserHeader(loginBean.getUsername());
                    }
                });
    }

    //从本地缓存中获取用户头像
    private void loadUserHeader(String userName) {
        String path = Hawk.get(Constants.HawkCode.HEADER_IMAGE + userName);
        if (!CommonUtils.isStringEmpty(path)) {
            userHeader.postValue(path);
        }
    }

    //设置用户信息
    public void setUserBean() {
        //从缓存中读取用户信息
        LoginBean data = Hawk.get(Constants.HawkCode.LOGIN_DATA);
        userBean.postValue(data);
        //读取本地缓存中的用户头像
        loadUserHeader(data.getUsername());
    }
}
